import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { getDb } from "@/db";
import { apiKey } from "@/db/api-key.schema";
import { eq, and } from "drizzle-orm";

// DELETE /api/keys/[id] - Delete an API key
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const keyId = params.id;

    // Check if the key exists and belongs to the user
    const db = await getDb();
    const [existingKey] = await db
      .select({ id: apiKey.id })
      .from(apiKey)
      .where(
        and(
          eq(apiKey.id, keyId),
          eq(apiKey.ownerType, "user"),
          eq(apiKey.ownerId, session.user.id)
        )
      );

    if (!existingKey) {
      return NextResponse.json({ error: "Key not found" }, { status: 404 });
    }

    // Delete the key
    await db
      .delete(apiKey)
      .where(
        and(
          eq(apiKey.id, keyId),
          eq(apiKey.ownerType, "user"),
          eq(apiKey.ownerId, session.user.id)
        )
      );

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Error deleting API key:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}